package com.nord.EventList;

import java.util.HashMap;
import java.util.List;

import com.nord.R;
import com.nord.R.id;
import com.nord.R.layout;
import com.nord.WebTools.HtmlBrowser;

import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class EventListAdapter extends SimpleAdapter {

	Context context;
	List<HashMap<String, String>> data;

	public EventListAdapter(Context context,
			List<HashMap<String, String>> data, int resource, String[] from,
			int[] to) {
		super(context, data, resource, from, to);
		this.context = context;
		this.data = data;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {

		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View rowView = inflater.inflate(R.layout.list_event, parent, false);

		final TextView eventname = (TextView) rowView.findViewById(R.id.eventname);
		final TextView eventdate = (TextView) rowView.findViewById(R.id.eventdate);
		final TextView countdown = (TextView) rowView.findViewById(R.id.countdown);

		eventname.setText(data.get(position).get("title"));
		eventdate.setText("Atburður hefst: " + prettyDate(data.get(position).get("date")));
		long milliseconds = Long.parseLong(data.get(position).get("start"));
		if (milliseconds > 0) {
			timerFunk(milliseconds, "hefst", countdown);
		} else {
			countdown.setTextColor(Color.RED);
			milliseconds = Long.parseLong(data.get(position).get("end"));
			timerFunk(milliseconds, "lýkur", countdown);
		}
		return rowView;
	}

	void timerFunk(long milliseconds, final String state,
			final TextView countdown) {
		if (milliseconds > 0) {
			new CountDownTimer(milliseconds, 1000 * 60) {
				@Override
				public void onTick(long milliseconds) {
					int minutes = (int) ((milliseconds / (1000 * 60)) % 60);
					int hours = (int) ((milliseconds / (1000 * 60 * 60)) % 24);
					int days = (int) ((milliseconds / 86400000));

					countdown.setText("Skráningu lýkur eftir: " + days + "d : " + hours + "h : " + minutes + "m");
				}

				@Override
				public void onFinish() {
					countdown.setTextColor(Color.GREEN);
					countdown.setText("Skráning er hafin!");
				}
			}.start();
		} else {
			countdown.setTextColor(Color.GRAY);
			countdown.setText("Skráningu er lokið");

		}
	}
	
	private String prettyDate(String date) {
		String[] split = date.split("T");
		String[] dates = split[0].split("-");
		return split[1] + " " + dates[2] + "/" +dates[1] + "/" + dates[0];
	}
}
